<template>
  <view>
    <!-- 搜索输入框 -->
    <view class="search-container">
      <uni-search-bar @input="input" cancelButton="none" radius="20" bgColor="#ffffff" focus="true" ></uni-search-bar>
    </view>
    
    <!-- 关键词搜索结果 -->
    <view class="search-result" v-if="searchResult.length > 0">
      <view class="result-item" v-for="(item, i) in searchResult" :key="i">
        <view class="result-item-name">{{item.goods_name}}</view>
        <uni-icons type="arrowright"></uni-icons>
      </view>
    </view>
    
    <!-- 搜索历史 -->
    <view class="search-history" v-else>
      <view class="search-clear">
        <text>搜索历史</text>
        <uni-icons type="trash" size="24" @click="clearHistory"></uni-icons>
      </view>
      <view class="search-key">
        <uni-tag class="search-key-item" @click="gotoGoodsList(item)" type="primary" v-for="(item, i) in searchKeys" :key="i" :text="item"></uni-tag>
      </view>
    </view>
  </view>
</template>

<script>
  export default {
    data() {
      return {
        timerId: null, // 防抖tiemrId
        kw: '', //搜索关键词
        searchResult: [], // 关键词搜索结果
        searchKeys: JSON.parse( uni.getStorageSync('kw') || '[]' ), // 用户搜索历史
      };
    },
    onLoad() {
      // 读取搜索历史
      // this.searchKeys = JSON.parse( uni.getStorageSync('kw') || '[]' )
    },
    methods:{
      // 用户输入事件处理函数
      input(value){
        clearTimeout(this.timerId)
        
        console.log(value)
        this.timerId = setTimeout(() => {
          // 检查判断一下value是否为空
          // if(!value.trim()) return
          
          if(value.trim()){
            this.kw = value
            console.log('发起搜索', this.kw)
            // 发起网络请求
            this.getSearchResult()
            // 保存搜索历史
            this.saveHistory()
          }else{
            // 清空搜索结果列表
            this.searchResult = []
          }
          
        }, 500)
      },
      // 获取关键词搜索结果
      async getSearchResult(){
        const {data: res} = await uni.$http.get('/goods/qsearch', {query: this.kw})
        console.log(res)
        // 数据异常判断
        if(res.meta.status !== 200) return uni.$showMsg()
        // 设置页面数据
        this.searchResult = res.message
      },
      // 保存搜索历史
      saveHistory(){
        // 现查找是否保存过？
        // 保存过，删除，追加到开头
        // 没有保存过，直接追加
        const index = this.searchKeys.indexOf(this.kw)
        if(index>=0){ // 找到了
           // 删除找到的元素
          // this.searchKeys.unshift(this.searchKeys.splice(index, 1))
          
          this.searchKeys = [...this.searchKeys.splice(index, 1), ...this.searchKeys]
        }else{ // 没找到
          this.searchKeys.unshift(this.kw)
        }
        
        // 持久化存储搜索历史
        uni.setStorageSync('kw', JSON.stringify(this.searchKeys))
      },
      
      // 清空搜索历史
      clearHistory(){
        this.searchKeys = []
        uni.setStorageSync('kw', JSON.stringify(this.searchKeys))
      },
      // 点击搜索历史跳转商品列表页
      gotoGoodsList(item){
          uni.navigateTo({
            url: '/subpkg/goods_list/goods_list?query=' + item
          })
      }
    }
  }
</script>

<style lang="scss">
  page {
    background-color: #ffffff;
  }
  
  .search-container {
    background-color: #c00000;
    position: sticky;
    top: 0;
  }
  
  .search-result {
    .result-item{
      display: flex;
      justify-content: space-between;
      height: 80rpx;
      align-items: center;
      border-bottom: 1rpx solid #efefef;
      margin: 0 16rpx;
      .result-item-name {
        overflow: hidden;  
        white-space: nowrap;  
        text-overflow: ellipsis;
        font-size: 24rpx;
      }
    }
  }
  
  .search-history {
    .search-clear {
      height: 80rpx;
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 0 16rpx;
      border-bottom: 1rpx solid #efefef;
    }
    .search-key {
      height: 80rpx;
      display: flex;
      align-items: center;
      .search-key-item {
        margin: 0 16rpx;
      }
    }
  }
  
</style>
